//
//  LoginViewController.swift
//  Jock
//
//  Created by HD on 15/4/5.
//  Copyright (c) 2015年 Haidy. All rights reserved.
//

import UIKit

class LoginViewController: UIViewController {
    
    private var loginView: LoginView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "登录"
        loginView = ViewUtil.instanceView("LoginView") as! LoginView
        loginView.frame = self.view.frame
        self.view.addSubview(loginView)
        loginView.loginButton.click { (button) -> Void in
            self.login()
        }
    }
    
    private func login() {
        HttpClient().Post("http://m2.qiushibaike.com/user/signin",para: getLoginBody(), response: { (response) -> Void in
            var loginMessage = LoginMessage.parser(JSON(data: response.data!))
            if loginMessage.err == 0 { //登录成功
                self.saveLoginMessage(loginMessage)
                self.navigationController?.popViewControllerAnimated(true)
            } else {
                println("登录失败")
            }
        }) { (error) -> Void in
            println("error")
        }
    }
    
    //保存登录信息
    private func saveLoginMessage(message: LoginMessage) {
        var config = AppConfig()
        message.saveValue(config)
    }
    
    //获取登录body
    private func getLoginBody() -> NSData {
        let uid = self.loginView.uidField.text
        let pwd = self.loginView.pwdField.text
        let json: JSON = ["login": uid, "pass": pwd]
        return json.description.removeBlank().toData(NSUTF8StringEncoding)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
